package com.pingpang.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingpang.service.UserService;
import com.pingpang.util.PageUtil;
import com.pingpang.util.StringUtil;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.ChartUser;


@RestController
@RequestMapping("/userController")
public class UserController {

	@Autowired
	private UserService userService;
	
	/**
	 * 后台管理界面
	 * @return
	 */
	@RequestMapping("/adminView")
	public ModelAndView adminView() {
		return new ModelAndView("regist");
	}
	
	/**
	 * 后台管理主页   
	 * @return
	 */
	@RequestMapping("/welcome")
	public ModelAndView welcome() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		

		/**
		   * 统计注册用户和登录用户数
		 */
		//int userCount=userService.getAllUserCount(new HashMap<String,String>());
		int userCount=userService.getAllRedisUser();
		int loginCount=ChannelManager.getAllUser().size();
		
		/**
		  * 统计注册用户数据 开始
		 */
		List<Map<String,String>> registCount=userService.getUserRegsitCount(7);
		List<String> dayList=new ArrayList<String>();
		List<String> countList=new ArrayList<String>();
		for(Map<String,String> map:registCount) {
			dayList.add(map.get("TODAY"));
			countList.add(map.get("COUNT"));
		}

		/**
		   * 面板1
		 */
		request.setAttribute("userDate", "['用户总数','上线总数']");
		request.setAttribute("userCount","[{value:"+userCount+", name:'用户总数'},{value:"+loginCount+", name:'上线总数'}]");
		
		/**
		   * 面板2
		 */
		request.setAttribute("dbRegistUserDate", "['"+String.join("','",dayList)+"']");
		request.setAttribute("dbRegistUserCount","['"+String.join("','",countList)+"']");
		
		return new ModelAndView("welcome");
	}
	
	/**
	 *  添加用户
	 * @return
	 */
	@RequestMapping(value="/regist")
	public ModelAndView userRegist(){
		return new ModelAndView("regist");
	}
	
	/**
	 *  添加用户
	 * @return
	 */
	@RequestMapping(value="/addUser")
	public ModelAndView addUser(ChartUser cu){
		cu.setUserStatus("0");//设置位离线
		Map<String,Object> addMap=userService.addUser(cu);
		
		ModelAndView mav = new ModelAndView();
		
		if(!"S".equals(addMap.get("CODE"))){
			mav.setViewName("regist");
        	mav.addObject("errorMsg", addMap.get("MESSAGE"));
        	return mav;
		}
		return new ModelAndView("index");
	}
	
	
	//----------------------在线用户数据开始----------------------
	/**
	 * 会员列表页面
	 * @return
	 */
	@RequestMapping("/online-member-list")
	public ModelAndView onlineMemberList() {
		return new ModelAndView("online-member-list");
	}
	
	
	/**
	 * 获取用户信息
	 */
	@ResponseBody
	@RequestMapping(value="/online-list")
	public Map<String,Object> onlineGetlistData(@RequestBody Map<String,String> queryMap) throws JsonParseException, JsonMappingException, IOException{
		queryMap.putAll(PageUtil.getPage(queryMap.get("page"), queryMap.get("limit")));
		ObjectMapper mapper = new ObjectMapper(); 
		if(!StringUtil.isNUll(queryMap.get("search"))) {
			queryMap.putAll(mapper.readValue(queryMap.get("search"), Map.class));
			queryMap.remove("search");
		}
		
		Set<ChartUser> userList=ChannelManager.getAllUser();
		Set<ChartUser> userListSearch=new HashSet<ChartUser>();
		//userList.iterator().
		for(ChartUser cu:userList) {
			if(!StringUtil.isNUll(queryMap.get("userCode"))) {
				if(cu.getUserCode().contains(queryMap.get("userCode"))){
					userListSearch.add(cu);
					continue;
				}
			}
			
			if(!StringUtil.isNUll(queryMap.get("userName"))) {
				if(cu.getUserName().contains(queryMap.get("userName"))){
					userListSearch.add(cu);
					continue;
				}
			}
			
		}
		
		Map<String,Object>resultMap=new HashMap<String,Object>();
		resultMap.put("code", "0");
		resultMap.put("msg", "");
		resultMap.put("page", queryMap.get("page"));
		resultMap.put("limit", queryMap.get("limit"));
		
		if(!StringUtil.isNUll(queryMap.get("userCode")) || !StringUtil.isNUll(queryMap.get("userName"))) {
			resultMap.put("count", userListSearch.size());
			resultMap.put("data", userListSearch);
		}else {
			resultMap.put("count", ChannelManager.getAllUser().size());
			resultMap.put("data", userList);
		}
		return resultMap;
	}
	
	/**
	 * 下线
	 * @param code
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/online-downUser",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDownUser(@RequestParam("id") String code) throws Exception {
		ChartUser cu=ChannelManager.getChartUser(code);
		cu.setUserStatus("0");//离线
		
		ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已禁言!");
		userService.dbDownUser(code, "0");
    	return StringUtil.returnSucess();
    }
    
    /**
	 * 上线
	 * @param code
	 * @return
	 * @throws Exception
	 */
   @RequestMapping(value="/online-upUser",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineUpUser(@RequestParam("id") String code) throws Exception {
		ChartUser cu=ChannelManager.getChartUser(code);
		cu.setUserStatus("1");//上线
		ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已上线!");
		userService.dbDownUser(code, "1");
   	    return StringUtil.returnSucess();
	}
   
    /**
	 *  注销
	 * @param code
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/online-delUser",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDelUser(@RequestParam("id") String code) throws Exception {
    	ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已下线!");
		ChannelManager.removeChannelByCode(code);
		userService.dbDownUser(code, "-1");
 	    return StringUtil.returnSucess();
	}
    
    
    /**
	 * 下线
	 * @param code
	 * @return
	 * @throws Exception
	 */
   @RequestMapping(value="/online-downUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDownUserAll(@RequestParam("ids") String code) throws Exception {
	    if(StringUtil.isNUll(code)) {
	    	return StringUtil.returnSucess();
	    }
        String[]codeArray=code.split(",",-1);
        
        for(String str:codeArray) {
        	ChartUser cu=ChannelManager.getChartUser(str);
        	cu.setUserStatus("0");//离线
        	ChannelManager.sendAlertMsgByCode(str, "系统消息此用户已禁言!");
        	userService.dbDownUser(str, "0");
        }
   	    return StringUtil.returnSucess();
   }
   
   /**
	 * 上线
	 * @param code
	 * @return
	 * @throws Exception
	 */
  @RequestMapping(value="/online-upUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineUpUserAll(@RequestParam("ids") String code) throws Exception {
	  if(StringUtil.isNUll(code)) {
	    	return StringUtil.returnSucess();
	    }
      String[]codeArray=code.split(",",-1);
      
      for(String str:codeArray) {
      	ChartUser cu=ChannelManager.getChartUser(str);
      	cu.setUserStatus("1");//上线
      	ChannelManager.sendAlertMsgByCode(str, "系统消息此用户已上线!!");
        userService.dbDownUser(cu.getUserCode(),"1");
      }
  	    return StringUtil.returnSucess();
	}
  
   /**
	 *  注销
	 * @param code
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value="/online-delUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlineDelUserAll(@RequestParam("ids") String code) throws Exception {
	   if(StringUtil.isNUll(code)) {
	    	return StringUtil.returnSucess();
	    }
       String[]codeArray=code.split(",",-1);
       
       for(String str:codeArray) {
    	   //ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已下线!");
    	   ChannelManager.removeChannelByCode(str);
    	   userService.dbDownUser(str,"-1");
       }
	    return StringUtil.returnSucess();
	}
   
    
    /**
	 * 消息广播
	 * @param code
	 * @return
	 * @throws Exception
	 */
  @RequestMapping(value="/online-sendUserAll",method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> onlinsendUserAll(@RequestParam("ids") String code,@RequestParam("msg") String msg) throws Exception {
	   if(StringUtil.isNUll(code) || StringUtil.isNUll(msg)) {
	    	return StringUtil.returnSucess();
	    }
     String[]codeArray=code.split(",",-1);
     
     for(String str:codeArray) {
    	 ChannelManager.sendAlertMsgByCode(str, msg);
     }
	    return StringUtil.returnSucess();
	}
    
 //----------------------在线用户数据结束----------------------
   
   
   
 //----------------------DB用户数据开始----------------------
 	/**
 	 * 会员列表页面
 	 * @return
 	 */
 	@RequestMapping("/db-member-list")
 	public ModelAndView dbMemberList() {
 		return new ModelAndView("db-member-list");
 	}
 	
 	
 	/**
 	 * 获取用户信息
 	 */
 	@ResponseBody
 	@RequestMapping(value="/db-list")
 	public Map<String,Object> dbGetlistData(@RequestBody Map<String,String> queryMap) throws JsonParseException, JsonMappingException, IOException{
 		queryMap.putAll(PageUtil.getPage(queryMap.get("page"), queryMap.get("limit")));
 		ObjectMapper mapper = new ObjectMapper(); 
 		if(!StringUtil.isNUll(queryMap.get("search"))) {
 			queryMap.putAll(mapper.readValue(queryMap.get("search"), Map.class));
 			queryMap.remove("search");
 		}
 		
 		Map<String,Object>resultMap=new HashMap<String,Object>();
 		resultMap.put("code", "0");
 		resultMap.put("msg", "");
 		resultMap.put("page", queryMap.get("page"));
 		resultMap.put("limit", queryMap.get("limit"));
 		resultMap.put("count", this.userService.getAllUserCount(queryMap));
 		resultMap.put("data",this.userService.getAllUser(queryMap));
 		return resultMap;
 	}
 	
 	/**
 	  * 下线
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
     @RequestMapping(value="/db-downUser",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDownUser(@RequestParam("id") String code) throws Exception {
 		ChartUser cu=ChannelManager.getChartUser(code);
 		if(null!=cu) {
 			ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已离线!");
 			cu.setUserStatus("0");//离线
 		}
 		Set<String>userCodeSet=new HashSet<String>();
 		userCodeSet.add(code);
 		
        this.userService.dbDownUser(userCodeSet, "0"); 		
     	return StringUtil.returnSucess();
     }
     
     /**
 	  * 上线
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
    @RequestMapping(value="/db-upUser",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbUpUser(@RequestParam("id") String code) throws Exception {
 		ChartUser cu=ChannelManager.getChartUser(code);
 		if(null!=cu) {
 			ChannelManager.sendAlertMsgByCode(code, "系统消息此用户已上线!");
 			cu.setUserStatus("1");//上线
 		}
 		
 		Set<String>userCodeSet=new HashSet<String>();
 		userCodeSet.add(code);
 		
        this.userService.dbDownUser(userCodeSet, "1"); 	
 		
    	return StringUtil.returnSucess();
 	}
    
     /**
 	   *  注销
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
     @RequestMapping(value="/db-delUser",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDelUser(@RequestParam("id") String code) throws Exception {
 		ChannelManager.removeChannelByCode(code);
 		
 		Set<String>userCodeSet=new HashSet<String>();
 		userCodeSet.add(code);
 		
        this.userService.dbDownUser(userCodeSet, "-1"); 	
 		
  	    return StringUtil.returnSucess();
 	}
     
     
     /**
 	  * 下线
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
    @RequestMapping(value="/db-downUserAll",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDownUserAll(@RequestParam("ids") String code) throws Exception {
 	    if(StringUtil.isNUll(code)) {
 	    	return StringUtil.returnSucess();
 	    }
         String[]codeArray=code.split(",",-1);
         
         for(String str:codeArray) {
         	ChartUser cu=ChannelManager.getChartUser(str);
         	 if(null!=cu) {
         	   ChannelManager.sendAlertMsgByCode(str, "系统消息此用户已离线!");
         	   cu.setUserStatus("0");//离线
         	 }
         }
         
         Set<String>userCodeSet=new HashSet<String>();
  		 userCodeSet.addAll(Arrays.asList(codeArray));
  		 this.userService.dbDownUser(userCodeSet, "0"); 	
         
    	 return StringUtil.returnSucess();
    }
    
    /**
 	  * 上线
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
   @RequestMapping(value="/db-upUserAll",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbUpUserAll(@RequestParam("ids") String code) throws Exception {
 	  if(StringUtil.isNUll(code)) {
 	    	return StringUtil.returnSucess();
 	    }
       String[]codeArray=code.split(",",-1);
       
       for(String str:codeArray) {
       	ChartUser cu=ChannelManager.getChartUser(str);
       	 if(null!=cu) {
       		ChannelManager.sendAlertMsgByCode(str, "系统消息此用户已上线!");
        	cu.setUserStatus("1");//上线
       	 }
       }
       
       Set<String>userCodeSet=new HashSet<String>();
	   userCodeSet.addAll(Arrays.asList(codeArray));
	   this.userService.dbDownUser(userCodeSet, "1"); 
       
   	    return StringUtil.returnSucess();
 	}
   
    /**
 	   *  注销
 	 * @param code
 	 * @return
 	 * @throws Exception
 	 */
    @RequestMapping(value="/db-delUserAll",method=RequestMethod.POST)
 	@ResponseBody
 	public  Map<String,Object> dbDelUserAll(@RequestParam("ids") String code) throws Exception {
 	   if(StringUtil.isNUll(code)) {
 	    	return StringUtil.returnSucess();
 	    }
        String[]codeArray=code.split(",",-1);
        
        for(String str:codeArray) {
           //ChannelManager.sendAlertMsgByCode(str, "系统消息此用户已注销!");
     	   ChannelManager.removeChannelByCode(str);
        }
        
        Set<String>userCodeSet=new HashSet<String>();
 		userCodeSet.addAll(Arrays.asList(codeArray));
 		this.userService.dbDownUser(userCodeSet, "-1"); 
 		 
 	    return StringUtil.returnSucess();
 	}
  //----------------------DB用户数据结束----------------------   
   
}
